#!/usr/bin/python
# coding=utf-8


# List of members of parliament
import urllib
import urlparse
import re
from openpolitics.feedreader.readers import sejmgovpl
from helpers import read_url

patterns = {
    'party_block': re.compile('<td valign="TOP"><a name', re.I|re.M),
    'name': re.compile('<strong>([^<]+)</strong>', re.I|re.M),
    'shortname': re.compile('<strong>[^<]+</strong><br>\s*\(([^\)]+)\)', re.I|re.M),
    'logo': re.compile('<img src="([^"]+)" alt=', re.I|re.M),
    'type': re.compile('<td width="320">([^<]+)<br>', re.I|re.M),
    'www': re.compile('<td align=left>.*?<a href="([^"]+)">www</a></td>', re.I|re.M),
    'page': re.compile('<td align=left><a href="([^"]+)">kontakt</a></td>', re.I|re.M),
    'members_url':  re.compile('<a href="(kluby/pos_[^"]+)">[0-9]+&nbsp;pos', re.I|re.M),
}

def join_url(base, url):
    if not url:
        return None
    return urlparse.urljoin(base, url)

def decode(string):
    if string:
        return unicode(string.decode(sejmgovpl.SETTINGS['encoding']))
    return u''

def get_name(soup):
    match = patterns['name'].search(soup)
    return match.group(1)

def get_shortname(soup):
    try:
        match = patterns['shortname'].search(soup)
        return match.group(1)
    except:
        return None

def get_logo(soup):
    try:
        match = patterns['logo'].search(soup)
        return match.group(1)
    except:
        return None

def get_logo(soup):
    try:
        match = patterns['logo'].search(soup)
        return match.group(1)
    except:
        return None

def get_www(soup):
    try:
        match = patterns['www'].search(soup)
        return match.group(1)
    except:
        return None

def get_page(soup):
    try:
        match = patterns['page'].search(soup)
        return match.group(1)
    except:
        return None

def get_members_url(soup):
    match = patterns['members_url'].search(soup)
    return match.group(1)

def get_parties(path=None):
    if not path:
        path = 'http://sejm.gov.pl/poslowie/kluby.htm'
    source = read_url(path)
    parties = []
    
    party_blocks = source.split('<td valign="TOP"><a name')[1:]
    for party_block in party_blocks:
        party = {
            'name': decode(get_name(party_block)),
            'shortname': decode(get_shortname(party_block)),
            'logo': join_url(path, get_logo(party_block)),
            'www': get_www(party_block),
            'page': join_url(path, get_page(party_block)),
            'members_url': join_url(path, get_members_url(party_block)),
        }
        parties.append(party)
    return parties

def main():
    parties = get_parties()
    #for party in parties:
    #    print party
    
    
    

if __name__ == "__main__":
    main()
